<script setup lang="ts">
import {ref, reactive, onMounted} from 'vue'
import {ElMessage, ElForm} from 'element-plus'
import {getCategorySimpleList} from '@/api/mall/product/category'
import {getList, getPage, create, deleteById} from '@/api/dine/config/TimeRangeApi'
import {checkRole} from "@/utils/permission";

defineComponent({
  name: "DineTimeRange"
})

interface TimeRange {
  id?: number
  categoryId: number
  startTime: string
  endTime: string
}

interface TimeRangeOption {
  label: string
  value: string
}

interface TimeRangeForm {
  categoryId: number | string
  timeRange: Array<String>
}

const categories = ref<any[]>([])

const timeRangeOptions = ref<TimeRangeOption[]>([])
const generateTimeRangeOptions = () => {
  const options: TimeRangeOption[] = []
  for (let hour = 0; hour < 24; hour++) {
    for (let minute = 0; minute < 60; minute += 30) {
      const start = `${hour.toString().padStart(2, '0')}:${minute.toString().padStart(2, '0')}`
      let endHour = hour
      let endMinute = minute + 30
      if (endMinute === 60) {
        endHour = (hour + 1) % 24
        endMinute = 0
      }
      const end = `${endHour.toString().padStart(2, '0')}:${endMinute.toString().padStart(2, '0')}`
      options.push({
        label: `${start}~${end}`,
        value: `${start}~${end}`
      })
    }
  }
  timeRangeOptions.value = options
}

const timeRangeList = ref<TimeRange[]>([])
const form = reactive<TimeRangeForm>({
  categoryId: '',
  timeRange: []
})
const rules = {
  categoryId: [{required: true, message: '请选择分类', trigger: ['change', 'blur']}],
  timeRange: [{required: true, message: '请至少选择一个时间段', trigger: ['change', 'blur']}]
}
const loading = ref(false)
const formRef = ref<InstanceType<typeof ElForm>>()

// 获取分类列表
const fetchCategories = async () => {
  try {
    categories.value = await getCategorySimpleList()
  } catch (err) {
    ElMessage.error('获取分类列表失败')
  }
}

// 获取时段配置列表
const fetchTimeRanges = async () => {
  try {
    loading.value = true
    if (checkRole(['shop_admin'])) {
      timeRangeList.value = await getList()
    } else {
      timeRangeList.value = await getPage({pageNo: 1, pageSize: 30})
    }
  } catch (err) {
    ElMessage.error('获取时段配置失败')
  } finally {
    loading.value = false
  }
}

// 提交表单
const submitForm = async () => {
  if (!formRef.value) return
  await formRef.value.validate(async (valid) => {
    if (valid) {
      try {
        loading.value = true
        await create(form)
        ElMessage.success('添加成功')
        await fetchTimeRanges()
        formRef.value!.resetFields()
      } catch (err) {
        ElMessage.error('添加失败')
      } finally {
        loading.value = false
      }
    }
  })
}

// 删除时段配置
const handleDelete = async (id: number | string) => {
  try {
    await deleteById(id)
    ElMessage.success('删除成功')
    await fetchTimeRanges()
  } catch (err) {
    ElMessage.error('删除失败')
  }
}

const refreshData = async () => {
  await fetchCategories()
  await fetchTimeRanges()
}

onMounted(() => {
  generateTimeRangeOptions()
  refreshData()
})
</script>

<template>
  <div class="p-20px">
    <el-card v-hasRole="['shop_admin']" shadow="never" class="mb-20px">
      <template #header>
        <div class="flex flex-row items-baseline">
          <span>时段限定</span>
          <span class="text-#999">(不限定则默认为24小时)</span>
          <div class="flex-1"></div>
          <el-button @click="refreshData">
            <Icon class="mr-5px" icon="ep:refresh"/>
            刷新列表
          </el-button>
        </div>
      </template>

      <el-form
        ref="formRef"
        :model="form"
        :rules="rules"
        label-width="100px"
      >
        <el-form-item label="菜品分类" prop="categoryId">
          <el-select
            v-model="form.categoryId"
            placeholder="请选择菜品分类"
            style="width: 300px"
          >
            <el-option
              v-for="category in categories"
              :key="category.id"
              :label="category.name"
              :value="category.id"
            />
          </el-select>
        </el-form-item>

        <el-form-item label="点餐时段" prop="timeRange">
          <el-select
            v-model="form.timeRange"
            multiple
            placeholder="请选择时间段"
            style="width: 300px"
          >
            <el-option
              v-for="item in timeRangeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button
            type="primary"
            @click="submitForm"
            :loading="loading"
          >
            添加配置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <el-card shadow="never">
      <template #header>
        <div class="flex items-center justify-between">
          <span>已限定时段</span>
        </div>
      </template>

      <el-table
        :data="timeRangeList"
        v-loading="loading"
        style="width: 100%"
      >
        <el-table-column prop="categoryName" label="菜品分类" min-width="100"/>
        <el-table-column prop="timeRangeName" label="点餐时段" min-width="220"/>
        <el-table-column v-hasRole="['shop_admin']" label="操作" width="120" fixed="right">
          <template #default="{ row }">
            <el-button type="danger" link @click="handleDelete(row.id)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
  </div>
</template>
